const fs = require('fs')
const express = require('express')

// 1、创建一个路由容器
const router = express.Router()

const {
  getIndexJsonData,
  submitAddPostData,
  writeDataInEdit,
  submitEditPostData,
  deleteData
} = require('../business')

// 列表页面展示
router.get('/', (req, res) => {
  getIndexJsonData((err, students) => {
    if (err) {
      return res.status(500).send('Server Error...')
    }
    res.render('dashboard/index.html', {
      studentsInfo: students
    })
  })
})

// 跳转至新增页面
router.get('/add', (req, res) => {
  res.render('dashboard/common/add.html')
})
// 跳转至新增页面
router.get('/edit', (req, res) => {
  writeDataInEdit(req.query.id, (err, data) => {
    if (err) {
      return res.status(500).send('Server Error')
    }
    res.render('dashboard/common/edit.html', {
      editData: data
    })
  })
})
// 跳转至新增页面
router.get('/delete', (req, res) => {
  deleteData(req.query.id, (err) => {
    if (err) {
      return res.status(500).send('Server Error')
    }
    res.redirect('/')
  })
})

// 提交新增数据
router.post('/add', (req, res) => {
  submitAddPostData(req.body, (err) => {
    if (err) {
      return res.status(500).send('Server Error...')
    }
  })

  res.redirect('/')
})
// 提交新增数据
router.post('/edit', (req, res) => {
  submitEditPostData(req.body, (err) => {
    if (err) {
      return res.status(500).send('Server Error...')
    }
  })

  res.redirect('/')
})

module.exports = router